import { messages } from "share/common";
import React, { Component } from 'react';
import { Popover, Checkbox, Button, Icon, message, Tooltip } from 'antd'
import advancedSearchService from './advanced-search.service'
import 'styles/components/advanced-search/advanced-search-pinned-list.scss'

class AdvancedSearchPinnedList extends Component {

  state = {
    checkedValues: [],
    indeterminate: true,
    checkAll: true,
    collapsed: false,
    sourceList: [],
    loading: false,
    saving: false
  };

  componentDidMount() {
    const { tableName, pinnedList, onChange } = this.props;
    if(tableName) {
      this.setState({ loading: true });
      advancedSearchService.getPinnedList(tableName)
        .then(res => {
          let sourceList = res.data || [];
          let checkedValues = [];
          if(res.data) {
            checkedValues = sourceList
              .filter(criteria => !criteria.hide)
              .map(criteria => criteria.criteriaName);
          } else {
            checkedValues = pinnedList;
          }
          this.setState({
            sourceList,
            checkedValues
          }, () => {
            onChange && onChange(checkedValues);
          });
        })
        .finally(() => {
          this.setState({ loading: false })
        })
    }
  }

  renderFormPopoverTitle = () => (
    <div className='advanced-search-pinned-list-popover-title'>
      {messages('components.key1019')/*设置默认展开项*/}
      <Icon type="close" onClick={this.closePopover}/>
    </div>
  );

  closePopover = () => {
    this.setState({ collapsed: false });
  };

  onChangeCheckbox = checkedValues => {
    const { searchForm } = this.props;
    this.setState({
      checkedValues,
      indeterminate: checkedValues.length > 0 && checkedValues.length < searchForm.length,
      checkAll: checkedValues.length === searchForm.length
    });
  };

  onCheckAll = e => {
    const { searchForm } = this.props;
    let checkAll = e.target.checked;
    this.setState({
      checkedValues: checkAll ? searchForm.map(item => item.id) : [],
      indeterminate: false,
      checkAll
    })
  };

  onClickOk = () => {
    const { onChange, tableName, searchForm } = this.props;
    const { checkedValues, sourceList } = this.state;
    if(tableName) {
      this.setState({ saving: true });
      let pinnedList = searchForm.map(field => {
        let result = {
          hide: checkedValues.indexOf(field.id) === -1,
          criteriaName: field.id,
        };
        let sourceItem = sourceList.find(source => source.criteriaName === field.id);
        if(sourceItem)
          result.id = sourceItem.id;
        return result
      });
      advancedSearchService.setPinnedList(tableName, pinnedList)
        .then(res => {
          message.success(messages('components.key1020')/*条件保存成功*/);
          this.setState({ collapsed: false, sourceList: res.data });
          onChange && onChange(checkedValues);
        })
        .finally(() => {
          this.setState({ saving: false });
        })
    } else {
      this.setState({ collapsed: false });
      onChange && onChange(checkedValues);
    }
  };

  renderPopoverContent = () => {
    const { searchForm, pinnedList } = this.props;
    const { checkedValues, indeterminate, checkAll, saving } = this.state;
    return <div>
      <div className='advanced-search-pinned-list-popover-checkbox-container'>
        <Checkbox.Group onChange={this.onChangeCheckbox} value={checkedValues}>
          {searchForm.map(item => (
            <div>
              <Checkbox
                value={item.id}
                className='advanced-search-pinned-list-popover-checkbox'
              >
                {item.label}
              </Checkbox>
            </div>
          ))}
        </Checkbox.Group>
      </div>
      <div className='advanced-search-pinned-list-popover-footer'>
        <Checkbox
          indeterminate={indeterminate}
          checked={checkAll}
          onChange={this.onCheckAll}
        >
          {messages('components.key557')/*全选*/}
        </Checkbox>
        <div className='advanced-search-pinned-list-popover-footer-buttons'>
          <Button size='small' onClick={() => this.onChangeCheckbox(pinnedList)}>
            {messages('common.reset')/*重置*/}
          </Button>
          <Button size='small' type='primary' onClick={this.onClickOk} loading={saving}>
            {messages('common.ok')/*确定*/}
          </Button>
        </div>
      </div>
    </div>
  };

  render() {
    const { collapsed, loading } = this.state;
    const { pinnedList } = this.props;
    return (
      <Tooltip title={<span>{messages('components.key1019')/*设置默认展开项*/}</span>} placement='top'>
         <span className='advanced-search-pinned-list'>
        {loading ? <Icon type='loading'/> : (
          <Popover
            title={this.renderFormPopoverTitle()}
            content={this.renderPopoverContent()}
            placement='bottom'
            getPopupContainer={triggerNode => triggerNode.parentNode}
            autoAdjustOverflow={false}
            overlayClassName='advanced-search-pinned-list-popover'
            trigger='click'
            visible={collapsed}
          >
            <span onClick={this.toState(
              { collapsed: !collapsed },
              () => this.onChangeCheckbox(pinnedList)
            )}>
              <Icon type="setting" className='advanced-search-pinned-list-icon'/>
            </span>
          </Popover>
        )}
      </span>
      </Tooltip>
    );
  }
}

export default AdvancedSearchPinnedList;
